﻿using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using Lamex.Base;
using Lamex.Interface;
using Lamex.Library;
using Lamex.Library.CommonClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mNC.UI
{
    public partial class Frm_NC_CodeByOrder : frmBaseChild
    {
        Lamex.mNC.ucControls.ucShowPic ucShowPicList = null;
        DataTable dt_Parameter_Tools = new DataTable();
        DataTable dt_Parameter_Machine = new DataTable();
        //int Width_splitPanel;
        public Frm_NC_CodeByOrder()
        {
            InitializeComponent();
        }

        private void Frm_NC_CodeByOrder_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            DateEditFormat();
            dt_Parameter_Tools = Common.GetDataTable.Get_Parameter_Tools();
            dt_Parameter_Machine = Common.GetDataTable.Get_Parameter_Machine();
        }
        public void DateEditFormat()
        {
            this.dtOrderDate.Properties.DisplayFormat.FormatString = "yyyy-MM-dd";
            this.dtOrderDate.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            this.dtOrderDate.Properties.EditFormat.FormatString = "yyyy-MM-dd";
            this.dtOrderDate.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            this.dtOrderDate.Properties.Mask.EditMask = "yyyy-MM-dd";
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        public override void DoView(IButtonInfo sender)
        {
            SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
            DataTable dt = Common.GetDataTable.Get_OrderData(dtOrderDate.Text.Trim());
            DataTable dt_Creo = Common.GetDataTable.Get_NC_PN_AL_FeatData_Creo();
            gridMainData.DataSource = dt;
            #region 自动勾选查询数据存在【NC_PN_AL_FeatData_Creo】
            ////去掉重复值【Part_No】【Drawing_No】
            //DataView dv = new DataView(dt);
            //DataTable dt_Dist = dv.ToTable(true, new[] { "Part_No", "Drawing_No" });
            //if (dt_Dist.Rows.Count > 0)
            //{
            //    for (int i = 0; i < dt_Dist.Rows.Count; i++)
            //    {
            //        //先确定查询数据是否存在【nC_PN_AL_FeatData_Creo】
            //        DataRow[] dr = dt_Creo.Select("Part_No='" + dt_Dist.Rows[i]["Part_No"].ToString() + "' and DWG_NO='" + dt_Dist.Rows[i]["Drawing_No"].ToString() + "'");
            //        if (dr.Length > 0)
            //        {
            //            //【自动勾选存在NC_PN_AL_FeatData_Creo】找到一条或多条勾选即可【用原始Datatable（不去重复值前筛选）】
            //            DataRow[] rows = dt.Select("PART_NO='" + dt_Dist.Rows[i]["Part_No"].ToString() + "' and Drawing_No='" + dt_Dist.Rows[i]["Drawing_No"].ToString() + "'");
            //            for (int j = 0; j < rows.Length; j++)
            //            {
            //                int iIndex = dt.Rows.IndexOf(rows[j]);
            //                gvMainData.SelectRow(iIndex);
            //            }
            //        }
            //    }
            //}
            #endregion
            //每次刷新自动计算gridcontrol宽度
            int width_Sums =0;
            this.gvMainData.OptionsView.ColumnAutoWidth = false;
            for (int i = 0; i < gvMainData.Columns.Count; i++)
            {
                this.gvMainData.BestFitColumns();
                this.gvMainData.Columns[i].BestFit();//自动列宽
                width_Sums += gvMainData.Columns[i].Width;
            }
            splitContainerControl1.SplitterPosition = width_Sums + 110;
            SplashScreenTool.CloseSplashScreen();
        }
        /// <summary>
        /// 显示图纸
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvMainData_Click(object sender, EventArgs e)
        {
            gc_ShowPicture.Controls.Clear();
            int iRow = gvMainData.FocusedRowHandle;
            string DWGNo = gvMainData.GetRowCellDisplayText(iRow, "Drawing_No").ToString();//图纸号
            string PartNo = gvMainData.GetRowCellDisplayText(iRow, "Part_No").ToString();//物料号
            List<string> listPic = new List<string>();
            listPic = Common.GetShowPic.ShowPic_STD(DWGNo, PartNo);
            if (listPic.Count > 0)
            {
                ucShowPicList = new ucControls.ucShowPic();
                ucShowPicList.LoadImageList(listPic);
                ucShowPicList.Dock = DockStyle.Fill;
                gc_ShowPicture.Controls.Add(ucShowPicList);
            }
        }
        /// <summary>
        /// 批量转码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAllNC_Click(object sender, EventArgs e)
        {
            try
            {
                SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
                string path = @"\\Tx-fs10\tx-fs1\LAMEX\NC\Porgram\Panel\Aluminum\";
                int isums = 0, icount_true = 0, ierror = 0;
                List<string> OrderNum_Error = new List<string>();
                List<string> DWG_No_Error = new List<string>();
                List<string> Part_No_Error = new List<string>();
                DataTable dt_ConvertRecord = Common.GetTable.GetNCConvert_Record();
                string date_TS = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                //获取选中行号
                int[] rownumber = this.gvMainData.GetSelectedRows();
                if (rownumber.Length <= 0)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("请选择需要转码的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    SplashScreenTool.CloseSplashScreen();
                    return;
                }
                //根据行号获取相应行的数据
                foreach (var item in rownumber)
                {
                    isums++;
                    decimal qty = 0;//数量
                    DataRow row = this.gvMainData.GetDataRow(item);
                    string OrderNumber = row[0].ToString();//订单号 "PL1912030034";//
                    string PartNo = row[2].ToString();//物料号"3033261753"; //
                    string DWGNO = row[3].ToString();//图纸号
                    //插入临时表dt_ConvertRecord
                    DataRow dr = dt_ConvertRecord.NewRow();
                    dr["FOLLOW_NO"] = OrderNumber;
                    dr["PART_NO"] = PartNo;
                    dr["CONVERT_TIME"] = date_TS;
                    dr["CONVERT_USER"] = Lamex.Common.Loginer.CurrentUser.AccountName;
                    dt_ConvertRecord.Rows.Add(dr);

                    double tolerance = txtTolerance.Text.Trim().Length > 0 ? Convert.ToDouble(txtTolerance.Text.Trim()) : 0;//公差
                    DataTable dt_QTY = Common.GetDataTable.Get_FeatData_PartDetail_QTY(OrderNumber);
                    if (dt_QTY.Rows.Count > 0)
                        // qty = Convert.ToDecimal(dt_QTY.Rows[0]["Part_QTY"].ToString());
                        qty = Convert.ToDecimal(dt_QTY.Compute("SUM(Part_QTY)", ""));//dt_QTY.AsEnumerable().Select(d => Convert.ToDecimal(d.Field<string>("Part_QTY"))).Sum();
                    bool IsCustom = false;
                    bool IsTest = false;
                    DataTable dt_Cache = Common.GetCacheTable.Get_Cache_Table(PartNo, DWGNO, OrderNumber, tolerance, dt_Parameter_Tools, dt_Parameter_Machine, qty, IsCustom, IsTest);//缓存表
                    //首先判断临时dt_Cache数据是否规范
                    if (dt_Cache.Rows.Count > 0)
                    {
                        bool flag_error = false;
                        for (int i = 0; i < dt_Cache.Rows.Count; i++)
                        {
                            double EXPOSED_LENTH = dt_Cache.Rows[i]["EXPOSED_LENTH"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["EXPOSED_LENTH"].ToString()) : 0;
                            double PROCESS_DEPTH = dt_Cache.Rows[i]["PROCESS_DEPTH"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["PROCESS_DEPTH"].ToString()) : 0;
                            double INITIAL_HEIGHT = dt_Cache.Rows[i]["INITIAL_HEIGHT"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["INITIAL_HEIGHT"].ToString()) : 0;
                            double FACE_HEIGHT = dt_Cache.Rows[i]["FACE_HEIGHT"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["FACE_HEIGHT"].ToString()) : 0;
                            string TOOL_NO = dt_Cache.Rows[i]["TOOL_NO"].ToString();
                            double BLADE_LENTH = dt_Cache.Rows[i]["BLADE_LENTH"].ToString().Length > 0 ? Convert.ToDouble(dt_Cache.Rows[i]["BLADE_LENTH"].ToString()) : 0;
                            string sqlwhere = @"PART_NO='" + PartNo + "' and DWG_NO='" + DWGNO + "' and WORK_SURFACE='" + dt_Cache.Rows[i]["WORK_SURFACE"].ToString() + @"'
                           and FEATURE_TYPE='" + dt_Cache.Rows[i]["FEATURE_TYPE"].ToString() + "' and DEEP_CODE='" + dt_Cache.Rows[i]["DEEP_CODE"].ToString() + @"'
                           and COORD_X='" + dt_Cache.Rows[i]["COORD_X"].ToString() + "' ";
                            if (TOOL_NO.Trim().Length <= 0)
                            {
                                string update_sql = @"update [LamexMESManager].[dbo].[NC_PN_AL_TEMP001] set ERR_INFO='无匹配刀具' where " + sqlwhere + " ";
                                BaseBuildSql.ExecuteNonQuery(update_sql);
                                flag_error = true;
                                continue;
                            }
                            if (Math.Round((EXPOSED_LENTH - 5), 2) < Math.Round((FACE_HEIGHT - PROCESS_DEPTH), 2) || Math.Round(BLADE_LENTH, 2) < Math.Round((INITIAL_HEIGHT - PROCESS_DEPTH), 2))
                            {
                                string update_sql = @"update [LamexMESManager].[dbo].[NC_PN_AL_TEMP001] set ERR_INFO='刀具长度不足加工此特征' where " + sqlwhere + " ";
                                BaseBuildSql.ExecuteNonQuery(update_sql);
                                flag_error = true;
                                continue;
                            }

                        }
                        if (flag_error)
                        {
                            DWG_No_Error.Add(DWGNO);
                            Part_No_Error.Add(PartNo);
                            OrderNum_Error.Add(OrderNumber);
                            ierror = ierror + 1;
                            continue;
                        }

                        DataView dv = new DataView(dt_Cache);
                        dv.Sort = "DWG_NO,PART_NO,QTY_TYPE,WORK_SURFACE,SUBROUTINE,TOOL_DIA,COORD_X";
                        DataTable dtResult = dv.ToTable(true, new[] { "DWG_NO", "PART_NO", "QTY_TYPE", "WORK_SURFACE", "SUBROUTINE", "TOOL_DIA" });
                        DataTable dt_QTY_TYPE = dv.ToTable(true, new[] { "QTY_TYPE", "QTY" });
                        DataTable dt_SURFACE = dv.ToTable(true, new[] { "WORK_SURFACE" });
                        DataTable dt_SUBROUTINE = dv.ToTable(true, new[] { "SUBROUTINE" });
                        //分别以MLT/MOD作为大分类,再与加工面为小类，分别生成txt
                        for (int i = 0; i < dt_QTY_TYPE.Rows.Count; i++)
                        {
                            string out_put_txt = "";
                            //1、生成MAIN_HEAD文件【MLT】
                            out_put_txt = out_put_txt + Calculate.AL_MAIN.GET_AL_MAIN_HEAD(dt_Cache.Rows[0]["DWG_NO"].ToString(),
                                dt_Cache.Rows[0]["PART_NO"].ToString(),
                                "G54",
                                dt_QTY_TYPE.Rows[i]["QTY"].ToString());

                            for (int j = 0; j < dt_SURFACE.Rows.Count; j++)
                            {
                                //2、生成FACE_HEAD文件 
                                out_put_txt = out_put_txt + Calculate.AL_FACE.GET_AL_FACE_HEAD(
                                dt_Cache.Rows[0]["DWG_NO"].ToString(),
                                dt_Cache.Rows[0]["PART_NO"].ToString(),
                                "G54",
                                dt_QTY_TYPE.Rows[i]["QTY"].ToString(),
                                dt_SURFACE.Rows[j]["WORK_SURFACE"].ToString());
                                DataTable dtFace = dtResult.Select("QTY_TYPE='" + dt_QTY_TYPE.Rows[i]["QTY_TYPE"].ToString() + "' and WORK_SURFACE='" + dt_SURFACE.Rows[j]["WORK_SURFACE"].ToString() + "'").CopyToDataTable();
                                for (int k = 0; k < dtFace.Rows.Count; k++)
                                {
                                    //3、生成子程序                              

                                    if (dtFace.Rows[k]["SUBROUTINE"].ToString().Length < 0)
                                        continue;
                                    string str_SUBROUTINE = dtFace.Rows[k]["SUBROUTINE"].ToString().Substring(2, 4);


                                    //得到每个子程序完整的数据
                                    string DWG_NO = dtFace.Rows[k]["DWG_NO"].ToString();
                                    string PART_NO = dtFace.Rows[k]["PART_NO"].ToString();
                                    string QTY_TYPE = dtFace.Rows[k]["QTY_TYPE"].ToString();
                                    string WORK_SURFACE = dtFace.Rows[k]["WORK_SURFACE"].ToString();
                                    string str_SUBROUTINE1 = dtFace.Rows[k]["SUBROUTINE"].ToString();
                                    string TOOL_DIA = dtFace.Rows[k]["TOOL_DIA"].ToString();
                                    string sqlWhere = @"DWG_NO='" + DWG_NO + "' and PART_NO='" + PART_NO + "' and QTY_TYPE='" + QTY_TYPE + "' and WORK_SURFACE='" + WORK_SURFACE + @"'
                                        and SUBROUTINE='" + str_SUBROUTINE1 + "' and TOOL_DIA='" + TOOL_DIA + "' ";
                                    DataTable dt_TEMP = dt_Cache.Select(sqlWhere).CopyToDataTable();
                                    //临时表升序-【必须定义好排序字段的类型，如dtNew.Columns.Add("COORD_X", typeof(double))】
                                    DataView dvTemp = new DataView(dt_TEMP);
                                    dvTemp.Sort = "DWG_NO,PART_NO,QTY_TYPE,WORK_SURFACE,SUBROUTINE,TOOL_DIA,COORD_X";
                                    dt_TEMP = dvTemp.ToTable();
                                    //【初始高度】【加工深度】
                                    string PROCESS_DEPTH = dt_TEMP.Rows[0]["PROCESS_DEPTH"].ToString();
                                    string INITIAL_HEIGHT = dt_TEMP.Rows[0]["INITIAL_HEIGHT"].ToString();
                                    //DataRow[] dr = dt_Parameter_Machine.Select("MODULE_CODE='" + dt_TEMP.Rows[0]["MODULE_CODE"].ToString() + "'");
                                    //if (dr.Length > 0)
                                    //{
                                    //    //初始高度
                                    //    //取得第一条数据的加工面和深度代码
                                    //    string WORK_SURFACE1 = dt_TEMP.Rows[0]["WORK_SURFACE"].ToString();
                                    //    string DEEP_CODE1 = dt_TEMP.Rows[0]["DEEP_CODE"].ToString();
                                    //    //拼接成字段【初始高度】
                                    //    string colums_height = WORK_SURFACE1 + "_FEED_" + DEEP_CODE1;
                                    //    DataTable dtTemp = dr.CopyToDataTable();
                                    //    INITIAL_HEIGHT = dtTemp.Rows[0][colums_height].ToString().Trim().Length > 0 ?
                                    //       (Convert.ToDouble(dtTemp.Rows[0][colums_height].ToString()) + 2).ToString() : "";

                                    //    //拼接成字段【加工深度】
                                    //    string colums_depth = WORK_SURFACE1 + "_DEEP_" + DEEP_CODE1;
                                    //    PROCESS_DEPTH = dtTemp.Rows[0][colums_depth].ToString().Trim().Length > 0 ?
                                    //      (Convert.ToDouble(dtTemp.Rows[0][colums_height].ToString()) - Convert.ToDouble(dtTemp.Rows[0][colums_depth].ToString()) - 4).ToString() : "";
                                    //}
                                    switch (str_SUBROUTINE)
                                    {
                                        case "HOLE":
                                            out_put_txt = out_put_txt + Calculate.AL_HOLE.GET_AL_HOLE_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                "G54",
                                                dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "",
                                                Math.Round(Convert.ToDouble(dt_TEMP.Rows[0]["FACE_HEIGHT"].ToString()) + 60, 1).ToString("0.00"),
                                                Convert.ToDouble(dt_TEMP.Rows[0]["COORD_X"]).ToString("0.00"),//因前面设置了类型，故需要转化
                                                 dt_TEMP.Rows[0]["COORD_Y"].ToString(),
                                                 dt_TEMP.Rows[0]["COMPENSATION_NO"].ToString());
                                            out_put_txt = out_put_txt + Calculate.AL_HOLE.GET_AL_HOLE_CYCLE(dt_TEMP,
                                                INITIAL_HEIGHT.Length > 0 ? Convert.ToDouble(INITIAL_HEIGHT).ToString("0.00") : "",
                                                PROCESS_DEPTH.Length > 0 ? Convert.ToDouble(PROCESS_DEPTH).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_HOLE.GET_AL_HOLE_END();
                                            break;
                                        case "TAPP":
                                            out_put_txt = out_put_txt + Calculate.AL_TAPP.GET_TAPP_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "",
                                                 Math.Round(Convert.ToDouble(dt_TEMP.Rows[0]["FACE_HEIGHT"].ToString()) + 60, 1).ToString("0.00"),
                                                  Convert.ToDouble(dt_TEMP.Rows[0]["COORD_X"]).ToString("0.00"),//因前面设置了类型，故需要转化
                                                 dt_TEMP.Rows[0]["COORD_Y"].ToString(),
                                                 dt_TEMP.Rows[0]["COMPENSATION_NO"].ToString());
                                            out_put_txt = out_put_txt + Calculate.AL_TAPP.GET_AL_TAPP_CYCLE(dt_TEMP,
                                                INITIAL_HEIGHT.Length > 0 ? Convert.ToDouble(INITIAL_HEIGHT).ToString("0.00") : "",
                                                PROCESS_DEPTH.Length > 0 ? Convert.ToDouble(PROCESS_DEPTH).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_TAPP.GET_AL_TAPP_END(dt_TEMP.Rows[0]["FEATURE_TYPE"].ToString());
                                            break;
                                        case "LPCK":
                                            out_put_txt = out_put_txt + Calculate.AL_LPCK.GET_AL_LPCK_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                 dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                 "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_LPCK.GET_AL_LPCK_CYCLE(dt_TEMP);
                                            // (Convert.ToDouble(dt_TEMP.Rows[0]["COORD_X"]).ToString("0.00"),//因前面设置了类型，故需要转化
                                            // dt_TEMP.Rows[0]["COORD_Y"].ToString(),
                                            // dt_TEMP.Rows[0]["COMPENSATION_NO"].ToString(),
                                            //Math.Round(Convert.ToDouble(dt_TEMP.Rows[0]["FACE_HEIGHT"].ToString()) + 60, 1).ToString("0.00"),
                                            //INITIAL_HEIGHT.Length > 0 ? Convert.ToDouble(INITIAL_HEIGHT).ToString("0.00") : "",
                                            // PROCESS_DEPTH.Length > 0 ? Convert.ToDouble(PROCESS_DEPTH).ToString("0.00") : "",
                                            // dt_TEMP.Rows[0]["FEED_SPEED_H"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["FEED_SPEED_H"].ToString()).ToString("0.00") : "",
                                            // dt_TEMP.Rows[0]["FEED_SPEED_V"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["FEED_SPEED_V"].ToString()).ToString("0.00") : "",
                                            // "G54",
                                            //(Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_WIDTH"].ToString()) / 2 - Convert.ToDouble(dt_TEMP.Rows[0]["TOOL_DIA"].ToString()) / 2) + 0.01,
                                            // (Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_LENGTH"].ToString()) / 2 - Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_WIDTH"].ToString()) / 2) + 0.01,
                                            // (Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_LENGTH"].ToString()) - Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_WIDTH"].ToString())) + 0.02,
                                            // (Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_LENGTH"].ToString()) / 2 - Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_WIDTH"].ToString()) / 2) + 0.5,
                                            // (Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_WIDTH"].ToString()) - Convert.ToDouble(dt_TEMP.Rows[0]["TOOL_DIA"].ToString())) + 0.02,
                                            // (Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_WIDTH"].ToString()) / 2 - Convert.ToDouble(dt_TEMP.Rows[0]["TOOL_DIA"].ToString()) / 2) + 0.01);
                                            break;
                                        case "RPCK":
                                            out_put_txt = out_put_txt + Calculate.AL_RPCK.GET_AL_RPCK_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                 dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                 "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_RPCK.GET_AL_RPCK_CYCLE(dt_TEMP);
                                            // Convert.ToDouble(dt_TEMP.Rows[0]["COORD_X"]).ToString("0.00"),//因前面设置了类型，故需要转化
                                            //dt_TEMP.Rows[0]["COORD_Y"].ToString(),
                                            //dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                            //Math.Round(Convert.ToDouble(dt_TEMP.Rows[0]["FACE_HEIGHT"].ToString()) + 60, 1).ToString("0.00"),
                                            // INITIAL_HEIGHT.Length > 0 ? Convert.ToDouble(INITIAL_HEIGHT).ToString("0.00") : "",
                                            //PROCESS_DEPTH.Length > 0 ? Convert.ToDouble(PROCESS_DEPTH).ToString("0.00") : "",
                                            //dt_TEMP.Rows[0]["FEED_SPEED_H"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["FEED_SPEED_H"].ToString()).ToString("0.00") : "",
                                            //dt_TEMP.Rows[0]["FEED_SPEED_V"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["FEED_SPEED_V"].ToString()).ToString("0.00") : "",
                                            //"G54",
                                            //(Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_WIDTH"].ToString()) / 2 - Convert.ToDouble(dt_TEMP.Rows[0]["TOOL_DIA"].ToString()) / 2),
                                            //(Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_LENGTH"].ToString()) / 2 - Convert.ToDouble(dt_TEMP.Rows[0]["FILLIT_RADIUS"].ToString())),
                                            //(Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_WIDTH"].ToString()) - Convert.ToDouble(dt_TEMP.Rows[0]["FILLIT_RADIUS"].ToString()) * 2),
                                            //(Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_LENGTH"].ToString()) - Convert.ToDouble(dt_TEMP.Rows[0]["FILLIT_RADIUS"].ToString()) * 2),
                                            //(Convert.ToDouble(dt_TEMP.Rows[0]["SLOT_LENGTH"].ToString()) / 2 - Convert.ToDouble(dt_TEMP.Rows[0]["FILLIT_RADIUS"].ToString())) + 0.5,
                                            //(Convert.ToDouble(dt_TEMP.Rows[0]["FILLIT_RADIUS"].ToString()) - Convert.ToDouble(dt_TEMP.Rows[0]["TOOL_DIA"].ToString()) / 2));
                                            break;
                                        case "CPCK":
                                            out_put_txt = out_put_txt + Calculate.AL_CPCK.GET_AL_CPCK_HEAD(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                                 dt_TEMP.Rows[0]["TOOL_DIA"].ToString(),
                                                 "G54",
                                                 dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["ROTATE_SPEED"].ToString()).ToString("0.00") : "");
                                            out_put_txt = out_put_txt + Calculate.AL_CPCK.GET_AL_CPCK_CYCLE(dt_TEMP);
                                            //(dt_TEMP.Rows[0]["TOOL_NO"].ToString(),
                                            //Math.Round(Convert.ToDouble(dt_TEMP.Rows[0]["FACE_HEIGHT"].ToString()) + 60, 1).ToString("0.00"),
                                            // INITIAL_HEIGHT.Length > 0 ? Convert.ToDouble(INITIAL_HEIGHT).ToString("0.00") : "",
                                            //PROCESS_DEPTH.Length > 0 ? Convert.ToDouble(PROCESS_DEPTH).ToString("0.00") : "",
                                            //dt_TEMP.Rows[0]["FEED_SPEED_V"].ToString().Length > 0 ? Convert.ToDouble(dt_TEMP.Rows[0]["FEED_SPEED_V"].ToString()).ToString("0.00") : "",
                                            //   Convert.ToDouble(dt_TEMP.Rows[0]["COORD_X"]).ToString("0.00"),//因前面设置了类型，故需要转化
                                            //dt_TEMP.Rows[0]["COORD_Y"].ToString(),
                                            //   Convert.ToDouble(dt_TEMP.Rows[0]["FEATURE_DIA"].ToString()) / 2,
                                            //     Convert.ToDouble(dt_TEMP.Rows[0]["COORD_X"].ToString()) +
                                            //      (Convert.ToDouble(dt_TEMP.Rows[0]["FEATURE_DIA"].ToString()) / 2) -
                                            //       (Convert.ToDouble(dt_TEMP.Rows[0]["TOOL_DIA"].ToString()) / 2));
                                            break;
                                    }
                                }
                                //4、FACE_END文件
                                out_put_txt = out_put_txt + Calculate.AL_FACE.GET_AL_FACE_END(dt_SURFACE.Rows[j]["WORK_SURFACE"].ToString());
                            }
                            //5、生成MAIN_END文件【MLT】
                            out_put_txt = out_put_txt + Calculate.AL_MAIN.GET_AL_MAIN_END();
                            //6、生成txt    
                            string fileName = path + OrderNumber + "_" + PartNo + "_" + dt_QTY_TYPE.Rows[i]["QTY_TYPE"].ToString();
                            FileStream fs = new FileStream(fileName + "_L.NC", FileMode.Create);
                            Common.GetTxtFile.GetTxtNodes(fs, out_put_txt);
                            //7、复制一个R.NC的txt
                            File.Copy(fileName + "_L.NC", fileName + "_R.NC", true);
                            //8、修改R.NC文件机头代码为G55
                            Common.GetTxtFile.EditTxtNodes("G54", "G55", fileName + "_R.NC");
                            icount_true++;
                        }

                    }

                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("物料【" + PartNo + "】图纸【" + DWGNO + "】特征数据不存在,请确认!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                }
                DevExpress.XtraEditors.XtraMessageBox.Show("共【" + isums + "】个文件,成功【" + (icount_true / 2) + "】个,失败【" + ierror + "】个!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //把成功转换的记录插入到[NC_PN_AL_Manufacture_Convert_Record]
                DataTable dataTable = new DataTable();
                StringBuilder s3 = new StringBuilder();
                StringBuilder s4 = new StringBuilder();
                s3.AppendFormat(@" AND PART_NO NOT IN ('{0}')", string.Join("','", Part_No_Error.ToArray()));
                s4.AppendFormat(@" AND FOLLOW_NO NOT IN ('{0}')", string.Join("','", OrderNum_Error.ToArray()));
                if (dt_ConvertRecord.Select("1=1" + s3.ToString() + s4.ToString()).Length > 0)
                {
                    dataTable = dt_ConvertRecord.Select("1=1" + s3.ToString() + s4.ToString()).CopyToDataTable();
                    Lamex.Base.BaseBuildSql.ExcuteInsert(dataTable, "NC_PN_AL_Manufacture_Convert_Record");
                }
                if (ierror > 0)
                {
                    StringBuilder s1 = new StringBuilder();
                    StringBuilder s2 = new StringBuilder();
                    if (!Directory.Exists(@"D:\MESTemp"))
                        Directory.CreateDirectory(@"D:\MESTemp");
                    SaveFileDialog fileDialog = new SaveFileDialog();
                    fileDialog.Title = "导出错误列表";
                    fileDialog.InitialDirectory = @"D:\MESTemp\";//导出默认路径
                    fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
                    fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称
                    //DialogResult dialogResult = fileDialog.ShowDialog(this);
                    //if (dialogResult == DialogResult.OK)
                    //{
                    s1.AppendFormat(@" AND PART_NO IN ('{0}')", string.Join("','", Part_No_Error.ToArray()));
                    s2.AppendFormat(@" AND DWG_NO IN ('{0}')", string.Join("','", DWG_No_Error.ToArray()));
                    string sql = @"SELECT distinct
       [DWG_NO]
      ,[PART_NO]
      ,[WORK_SURFACE]
      ,[FEATURE_TYPE]
      ,[DEEP_CODE]
      ,[COORD_X]
      ,[FEATURE_DIA]
      ,[SLOT_LENGTH]
      ,[SLOT_WIDTH]
      ,[FILLIT_RADIUS]    
      ,[ERR_INFO]
  FROM [LamexMESManager].[dbo].[NC_PN_AL_TEMP001] where 1=1  AND ISNULL(ERR_INFO,'')!=''  " + s1.ToString() + " " + s2.ToString() + "";
                    DataTable dtTemp = BaseBuildSql.GetDataTableBySql(sql);
                    GridControl grid = new GridControl();
                    GridView view = new GridView();
                    grid.ViewCollection.Add(view);
                    grid.MainView = view;
                    view.GridControl = grid;
                    foreach (DataColumn dc in dtTemp.Columns)
                    {
                        DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
                        gridColumnNumber.FieldName = dc.ColumnName;
                    }
                    grid.DataSource = dtTemp;
                    this.Controls.Add(grid);
                    grid.ForceInitialize();//强制初始化
                                           //Font font = new Font("宋体", 11, FontStyle.Bold); 
                                           //view.Appearance.HeaderPanel.Font = font;
                                           //view.Appearance.Row.Font = font;            
                    view.BestFitColumns();
                    view.OptionsView.ColumnAutoWidth = false;
                    view.OptionsView.ShowAutoFilterRow = false;
                    view.OptionsPrint.PrintHorzLines = false;//去掉水平网格线
                    view.OptionsPrint.PrintVertLines = false;//去掉垂直网格线
                    view.ExportToXlsx(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");
                    //if (DevExpress.XtraEditors.XtraMessageBox.Show("生成错误信息列表成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    System.Diagnostics.Process.Start(fileDialog.InitialDirectory + fileDialog.FileName + ".xlsx");//打开指定路径下的文件
                    //}
                }
                DoView(null);
                SplashScreenTool.CloseSplashScreen();

            }
            catch (Exception ex)
            {
                SplashScreenTool.CloseSplashScreen();
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 自动定位至焦点行
        /// </summary>
        /// <param name="strDwg_Part_No">图纸号+部件号</param>
        public void GetFoucuseRowHandle(string strDwg_Part_No)
        {
            string searchText = strDwg_Part_No;
            // obtaining the focused view
            ColumnView view = (ColumnView)gridMainData.FocusedView;
            // obtaining the column bound to the Country field
            GridColumn column = view.Columns["Dwg_Part_No"];
            if (column != null)
            {
                // locating the row
                //如果用数据源中的列值，请用ColumnView.LocateByValue  LocateByDisplayText
                int rhFound = view.LocateByDisplayText(view.FocusedRowHandle + 1, column, searchText);
                // focusing the cell
                if (rhFound != GridControl.InvalidRowHandle)
                {
                    view.FocusedRowHandle = rhFound;
                    view.FocusedColumn = column;
                }
            }
        }
        /// <summary>
        /// 复制ctrl+C
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvMainData_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control & e.KeyCode == Keys.C)
            {
                Clipboard.SetDataObject(gvMainData.GetFocusedRowCellValue(gvMainData.FocusedColumn));
                e.Handled = true;
            }
        }

        private void Frm_NC_CodeByOrder_HelpRequested(object sender, HelpEventArgs hlpevent)
        {
            Help.ShowHelp(this, @"d:\数据库帮助文档.chm");
        }

        private void Frm_NC_CodeByOrder_Resize(object sender, EventArgs e)
        {
           // Width_splitPanel = splitContainerControl1.Width;
        }
    }
}
